package com.example.myapp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.apache.http.Header;

import java.io.File;



public class CompleteInfomationPhotoEditActivity extends Activity {
    private ClipImageView imageView;
    private TitleBar mTitleBar;
    Context mContext;
    ProgressBar Progress;
    private String headPortrait;
    String url;

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        setContentView(R.layout.activity_complete_infomation_photo_edit);
        mContext = this;
        doCreate();
    }


    protected void doCreate() {
        mTitleBar = (TitleBar) findViewById(R.id.titleBar_photos_edit);
        mTitleBar.setLeftImageResource(R.drawable.ic_launcher);
        mTitleBar.setBackgroundResource(R.drawable.ic_launcher);
        mTitleBar.setTitleTextColor(Color.WHITE);
        mTitleBar.setRightText("完成");
        mTitleBar.setTitleText("编辑头像");
        Progress = new ProgressBar(mContext);
        mTitleBar.setLeftImageClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mTitleBar.setRightClick(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(mContext,"正在上传...",Toast.LENGTH_SHORT).show();
                // 剪切生成图片
                Bitmap bitmap = imageView.clip();
                BitmapUtils.compressBitmap(bitmap, 512);

                String filename = "head" + System.currentTimeMillis() + ".png";
                String dirpath = CompleteInfomationPhotoEditActivity.this
                        .getExternalCacheDir() + "/renminheads";
                // 保存图片
                PhotoUtil.saveBitmap(dirpath, filename, bitmap, false);
                // 生成一个存放到本地的头像的url
                headPortrait = dirpath + "/" + filename;

                try {
                    // ！！！！！！！！！！gry 注意上传的接口
                    uploadFile(headPortrait, url);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });

        // 获得屏幕参数
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(dm);

        imageView = (ClipImageView) findViewById(R.id.src_pic);
        imageView.setClip_type(ClipImageView.TYPE_AVATAR);

        String imagepath = getIntent().getStringExtra("imagePath");
        Bitmap bitmap = BitmapUtils.getBitmapCompressed(this, imagepath, 450,
                600);
        bitmap = BitmapUtils.getRotateBitmap(imagepath, bitmap);
        imageView.setImageBitmap(bitmap);

        // 剪切的圆的图像
        ImageView iv = (ImageView) findViewById(R.id.ivCircle_middle);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) iv.getLayoutParams();
        // 圆的外接正方形的边长为屏幕的宽度
        params.height = dm.widthPixels;
    }

    public void uploadFile(String path, final String url) throws Exception {
        mTitleBar.setRightImageClickable(false);
        File file = new File(path);
        if (file.exists() && file.length() > 0) {
            AsyncHttpClient client = new AsyncHttpClient();
            client.setTimeout(30 * 1000);
            RequestParams params = new RequestParams();
            params.put("img", file);
            // 上传文件
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers,
                                      byte[] responseBody) {
                    // 上传成功后要做的工作
                    Toast.makeText(mContext, "上传成功", Toast.LENGTH_LONG).show();
                    String t = new String(responseBody);
                    t = GsonRequest.parseUnicode(t);
//                    System.out.println("---上传数据" + "----------" + t);
//                    Gson mGson = new Gson();
//                    UploadIconModule uploadImageModel = mGson.fromJson(t,
//                            UploadIconModule.class);
//
//                    if (url.equals("http://api.laoxiangbang.com.cn/index.php?m=Home&c=Api&a=uploadLogo")) {
//                        UserUtil.setCompanyInfologo(mContext,
//                                uploadImageModel.getData());
//                    } else if (url.equals("http://api.laoxiangbang.com.cn/index.php?m=Home&c=Api&a=uploadAvatar")) {
//                        System.err.println("本地头像" + uploadImageModel.getData());
//
//                        UserUtil.setuseravatar(mContext,
//                                uploadImageModel.getData());
//                    }

                    // 将上传成功的路径，返回给上级页面。
                    Intent result = new Intent();
                    result.putExtra("avatar_path", headPortrait);
                    setResult(RESULT_OK, result);
                    finish();

                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    mTitleBar.setRightImageClickable(true);
                    System.out.println("--->图片上传失败" + error.getMessage()
                            + statusCode);
                    // 上传失败后要做到工作
                    Toast.makeText(mContext, "上传失败，请重新上传", Toast.LENGTH_LONG)
                            .show();

                }

                @Override
                public void onProgress(int bytesWritten, int totalSize) {
                    super.onProgress(bytesWritten, totalSize);
                    int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
                    // 上传进度显示
                    Log.e("上传 Progress>>>>333>", count + "");
                    Log.e("上传 Progress>>>>>", bytesWritten + " / " + totalSize);
                }

                @Override
                public void onRetry(int retryNo) {
                    super.onRetry(retryNo);
                    // 返回重试次数
                }

            });
        } else {
            Toast.makeText(mContext, "文件不存在", Toast.LENGTH_LONG).show();
        }
    }
}
